package org.wisdomdata.writer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.wisdomdata.framework.DataWriter;


public class TextWriter implements DataWriter{
	 private static DateFormat dateFormatStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
	 
	 public void writeTables(Map<String, Map<String, List<String>>> ts, String rootDir, String suffix) throws IOException {
		
		File rootFile = new File(rootDir);
		
		Set<Entry<String, Map<String, List<String>>>> tables =  ts.entrySet();
		for (Entry<String, Map<String, List<String>>> table : tables) {
			List<String> columnNames = new ArrayList<String>();
			if (table != null) {
				File tableFile = new File(rootFile, table.getKey() + suffix);
				boolean needHeader = !tableFile.exists();
				FileWriter writer = new FileWriter(tableFile, true);
				
				Map<String, List<String>> t = table.getValue();
				Set<Entry<String,List<String>>> tentry = t.entrySet();
				int length = 0;
				String tempLine = "";
				for (Entry<String,List<String>> t2 : tentry) {
					if (t2 != null) {
						columnNames.add(t2.getKey());
						tempLine += t2.getKey() + ",";
						length = t2.getValue().size();
					}
				}
				tempLine += "CRAWL_TIME";
				tempLine += "\n";
				if (needHeader)
					IOUtils.write(tempLine, writer);
				for (int i = 0; i < length; i++) {
					tempLine = "";
					for (String column : columnNames) {
						tempLine += "{[" + t.get(column).get(i) + "]},";
					}
					tempLine += dateFormatStr.format(new Date(System.currentTimeMillis()));
					tempLine += "\n";
					IOUtils.write(tempLine, writer);
				}
				IOUtils.closeQuietly(writer);
			}
		}
	}
	
	
}
